#include <fstream>
#include <highgui.h>
#include <iostream>
#include "differences.hpp"

using namespace std;

int img_difference(char* file){
    IplImage* image;

    if( (image = cvLoadImage(file,1)) == 0 )      // wczytuje obrazek
        return -1;
    IplImage *temp_img = cvCloneImage(image);
    int width = temp_img->width;
    int height = temp_img->height;
    int nchannels = temp_img->nChannels;
    int step = temp_img->widthStep;

    uchar *data = ( uchar* )temp_img->imageData;

    int temp[4];
    int temp2[4];

    temp[0] = 0;
    temp[1] = 0;
    temp[2] = 0;
    temp[3] = 0;
    int roznica = 0;

    for(int i = 0 ; i < height ; i++ ){
        for(int j = 0 ; j < width ; j++ ){
            for(int l = 0; l<3; l++){
                temp2[l] = data[i*step + j*nchannels + l];
                roznica = data[i*step + j*nchannels + l] - temp[l];
                data[i*step + j*nchannels + l] = roznica+256;
                temp[l] =temp2[l];
            }
        }
    }

    cvSaveImage("temp.bmp", temp_img );
    cvReleaseImage(&image);                  // zwolnienie pami�ci obrazka�w
    cvReleaseImage(&temp_img);
    return 0;
}

int un_img_difference(char* file){
    IplImage* image;

    if((image = cvLoadImage("temp.bmp",1)) == 0 )      // wczytuje obrazek
        return -1;
    IplImage *temp_img = cvCloneImage(image);

    int width = temp_img->width;
    int height = temp_img->height;
    int nchannels = temp_img->nChannels;
    int step = temp_img->widthStep;

    uchar *data = ( uchar* )temp_img->imageData;

    int temp[4];
    temp[0] = 0;
    temp[1] = 0;
    temp[2] = 0;
    temp[3] = 0;


    for(int i = 0 ; i < height ; i++ ){
        for(int j = 0 ; j < width ; j++ ){
            if(i==0 && j==0)
                for(int l=0;l<3;l++)
                    temp[l] = data[i*step + j*nchannels + l];
            else
                for(int l=0;l<3;l++){
                    data[i*step + j*nchannels + l] = temp[l]+data[i*step + j*nchannels + l];
                    temp[l] = data[i*step + j*nchannels + l];
                }
        }
    }
    cvSaveImage(file, temp_img );
    cvReleaseImage(&image);                  // zwolnienie pami�ci obrazka�w
    cvReleaseImage(&temp_img);
    return 0;
}
